package com.tan.lbs.service.impl;

import java.util.ArrayList;

import com.tan.lbs.dao.DialogNodeDAO;
import com.tan.lbs.dao.DialogNodeOrderDAO;
import com.tan.lbs.dao.NPCDAO;
import com.tan.lbs.dao.impl.DialogNodeDAOImpl;
import com.tan.lbs.dao.impl.DialogNodeOrderDAOImpl;
import com.tan.lbs.dao.impl.NPCDAOImpl;
import com.tan.lbs.entity.DialogNode;
import com.tan.lbs.entity.DialogNodeOrder;
import com.tan.lbs.entity.DialogNodeInTree;
import com.tan.lbs.service.DialogService;

public class DialogServiceImpl implements DialogService {
	
	private DialogNodeDAO dialogNodeDAO;
	private DialogNodeOrderDAO dialogNodeOrderDAO;
	private NPCDAO npcDAO;
	
	public DialogServiceImpl() {
		dialogNodeDAO = new DialogNodeDAOImpl();
		dialogNodeOrderDAO = new DialogNodeOrderDAOImpl();
		npcDAO = new NPCDAOImpl();
	}


	@Override
	public DialogNodeInTree retrieveDialogInTree(String npcID) {
		return dialogNodeOrderDAO.searchByNPCInTreeByStartDialogNode(npcDAO.readByID(npcID).getDialogID());

	}


	@Override
	public DialogNode readDialogNodeDetails(String dialogNodeID) {
		return dialogNodeDAO.readByID(dialogNodeID);
	}
	
	@Override
	public void modifyDialogNodeDetails(DialogNode dialogNode) {
		dialogNodeDAO.update(dialogNode);
	}


	@Override
	public ArrayList<DialogNodeOrder> retrieveBranchesForFromDialogNode(String fromNodeID) {
		return dialogNodeOrderDAO.searchByFromDialogNode(fromNodeID);
	}


	@Override
	public ArrayList<String> createNewBranchForDialogNode(String dialogNodeID,String newNodeName) {
		DialogNode newDialogNode = new DialogNode();
		newDialogNode.setName(newNodeName);
		newDialogNode.setInteractionType("display");
		newDialogNode.setNodeType("progress");
		String newDialogNodeID = dialogNodeDAO.create(newDialogNode);
		DialogNodeOrder dialogNodeOrder = new DialogNodeOrder();
		dialogNodeOrder.setFromNodeID(dialogNodeID);
		dialogNodeOrder.setToNodeID(newDialogNodeID);
		String newDialogNodeOrderID = dialogNodeOrderDAO.create(dialogNodeOrder);
		ArrayList<String>  IDs = new ArrayList<String>();
		IDs.add(newDialogNodeID);
		IDs.add(newDialogNodeOrderID);
		return IDs;
	}


	@Override
	public void modifyBranchDetails(DialogNodeOrder dialogNodeOrder) {
		DialogNodeOrder modDialogNodeOrder  = dialogNodeOrderDAO.readByID(dialogNodeOrder.getOrderID());
		modDialogNodeOrder.setAnswer(dialogNodeOrder.getAnswer());
		dialogNodeOrderDAO.update(modDialogNodeOrder);
	}


	@Override
	public void deleteDialogNodeAndChildren(String dialogNodeID) {
		//Deal with parent node
		DialogNodeOrder parentLink = dialogNodeOrderDAO.readByToNode(dialogNodeID);
		dialogNodeOrderDAO.delete(parentLink.getOrderID());
		//Deal with children nodes
		dialogNodeOrderDAO.deleteAllChildrenUnderDialogNode(dialogNodeID);
	}



}
